# -*- coding: utf-8 -*-
from django.shortcuts import render,get_object_or_404, render_to_response
from django.http import HttpResponseRedirect,HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext, loader
from poudres.models import Poudre, Event, Type_Event
from poudres.forms import EventForm,PoudreForm, CommandeForm
from clients.models import Client
from django.utils import simplejson 
import re, json   

# Create your views here.
def autocompletion(request):
    if request.is_ajax():
        q = request.GET.get('term', '')   
        listeP = Poudre.objects.filter(nom__istartswith=q)
        results = []
        for p in listeP:
            tab_rep = {}
            tab_rep['value'] = p.nom+"-"+p.codeP
            
            results.append(tab_rep)
        data = simplejson.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

def search_poudre(request): 
    if request.is_ajax():
        q = request.GET.get('term', '')  
        question = re.sub(r'_', " ", q);
        p = get_object_or_404(Poudre,nom__exact=question)
        listeE = p.event_set.all()
        results = []
        for event in listeE:           
            results.append([event.TE.__unicode__(), event.date.strftime('%Y-%m-%d %H:%M:%S'), event.quantite.__str__(),event.prix.__str__(), event.somme.__str__(), event.instock.__str__()])
        data = simplejson.dumps(results)
    else:
        data = 'fail'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)
    
def poudre_index(request):
    liste_poudres = Poudre.objects.select_related().all()
    return render_to_response('poudres/liste_poudres.html',
                              {'liste_poudres': liste_poudres,
                               'titre':"Liste bột đã nhập"},
                              context_instance=RequestContext(request))
    
def details_poudre(request,id_poudre): 
    poudre = get_object_or_404(Poudre,pk=id_poudre)
    listeE = poudre.event_set.all()
    return render_to_response('poudres/poudre_events.html',
                              {'listeE': listeE,
                               'poudre': poudre,
                               'titre':"Chi tiết xuất nhập bột",
                               'PAGE_TITLE': 'Chi tiết xuất nhập bột' ,
                               'WEBSITE_TITLE': 'DNTN Kiều Anh'},
                              context_instance=RequestContext(request))
    
def accueil_poudre(request):
    return render_to_response('poudres/poudre_accueil.html',
                              {'PAGE_TITLE': 'Quản lí bột' ,'WEBSITE_TITLE': 'DNTN Kiều Anh'})

def poudre_addevent(request,id_poudre):
    p = Poudre.objects.get(pk=id_poudre)
    if request.method == 'POST':
        form = EventForm(request.POST)
        if form.is_valid():
            form.save()
            event = form.instance
            event.somme= event.prix*event.quantite
            if event.TE.id == 1:
                event.instock=p.instock+event.quantite
            elif event.TE.id == 2:
                event.instock=p.instock-event.quantite   
            p.instock = event.instock
            p.save()
            event.save()
            return HttpResponseRedirect('/poudres/details/%s/' %id_poudre)
        else:
            return HttpResponseRedirect('/poudres/details/%s/' %id_poudre)
    else:
        form = EventForm(initial={'poudre': p,'instock': 0,'somme':0})            
        return render_to_response('poudres/form/form_event.html',
                                    {'form': form,
                                     'poudre':p,
                                     'titre':"Xuất nhập bột!",
                                      'url': '/poudres/%s/addevent/' %id_poudre,},
                                      context_instance = RequestContext(request))

def addpoudre(request):
    if request.method == 'POST':
        form = PoudreForm(request.POST)
        if form.is_valid():
            form.save()
            id_poudre = form.instance.pk
            request.notifications.success((u"l'adresse mail a bien été ajoutée."))
            return HttpResponseRedirect('/poudres/details/%s/' %id_poudre)
        else:
            return HttpResponseRedirect('/poudres/')
    else:
        form = PoudreForm()            
        return render_to_response('poudres/form/form_poudre.html',
                                    {'form': form,
                                     'titre':"Tạo bột mới!",
                                      'url': '/poudres/addpoudre/'},
                                      context_instance = RequestContext(request))
    

    
    
